package com.st.springbootsse.service.impl;

import cn.hutool.core.util.IdUtil;
import com.st.springbootsse.event.CustomEvent;
import com.st.springbootsse.service.IndexService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangli
 */
@Service
public class IndexServiceImpl implements IndexService, ApplicationContextAware, ApplicationEventPublisherAware {

    private final Map<String, ScheduledExecutorService> scheduledExecutorMap = new ConcurrentHashMap<>();

    private final Map<String, Object> uidMap = new ConcurrentHashMap<>();

    @Override
    public void sendMessage(String uid) {
        // 创建一个uid
        uidMap.put(uid, uid);

        // 创建一个大小为5的定时线程池
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
        scheduledExecutorMap.put(uid, scheduledExecutorService);
        // 提交一个延迟1秒后开始执行，之后每隔2秒执行一次的任务
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                applicationEventPublisher.publishEvent(new CustomEvent(this, uid, IdUtil.fastUUID(), IdUtil.fastSimpleUUID()));
            }
        }, 1, 2, TimeUnit.SECONDS);
    }

    @Override
    public void closeSse(String uid) {
        uidMap.remove(uid);
        ScheduledExecutorService scheduledExecutorService = scheduledExecutorMap.remove(uid);
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
            try {
                // 等待所有任务完成，最多等待1分钟
                if (!scheduledExecutorService.awaitTermination(1, TimeUnit.MINUTES)) {
                    scheduledExecutorService.shutdownNow();
                }
            } catch (InterruptedException e) {
                scheduledExecutorService.shutdownNow();
            }
        } else {
            System.out.println("ScheduledExecutorService for uid " + uid + " not found.");
        }
    }





    private ApplicationContext applicationContext;
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}
